//
//  RechargeViewController.m
//  UniversalApp
//
//  Created by 志刚杨 on 2018/3/16.
//  Copyright © 2018年 voidcat. All rights reserved.
//

#import "RechargeViewController.h"
#import "RechargeListCollectionViewCell.h"
#import "PayOptionCollectionViewCell.h"
#import "payModel.h"
#import <UIImageView+WebCache.h>
#import "IAPManager.h"
#import "PayManager.h"
@interface RechargeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,IApRequestResultsDelegate>

@end

@implementation RechargeViewController
{
    QMUIFloatLayoutView *_rechargeList;
    UIButton *_payButton;
    NSInteger _selectPayID;
    NSInteger _selectPayItem;//充值金额id
    NSArray *_paylist;
    NSArray *_payOption;
    PayManager *_payManager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _selectPayID = 0;
    _selectPayItem = 0;
    [[IAPManager sharedIAPManager] startManager];
    [self createUI];
    [self getRechargeList];
    _payManager = [[PayManager alloc] init];
}

-(void)createUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    self.collectionView.collectionViewLayout = layout;
    layout.minimumLineSpacing = 4;//设置最小行间距
    layout.minimumInteritemSpacing = 3;//item间距(最小值)
    layout.sectionInset = UIEdgeInsetsMake(20, 3, 10, 3);//设置section的编距
    self.collectionView.backgroundColor = CViewBgColor;
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([RechargeListCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([RechargeListCollectionViewCell class])];
    
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([PayOptionCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([PayOptionCollectionViewCell class])];
    //
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader"];

    _payButton = [[UIButton alloc] init];
    [_payButton setTitle:ASLocalizedString(@"一键充值")forState:UIControlStateNormal];
    [_payButton setTitleColor:KWhiteColor forState:UIControlStateNormal];
    [_payButton setBackgroundColor:MainColor];
    [_payButton addTarget:self action:@selector(handleDoPayEvent:) forControlEvents:UIControlEventTouchUpInside];
    _payButton.frame = CGRectMake(0, KScreenHeight - 120, SCREEN_WIDTH, 55);
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.mj_header.hidden = YES;
    self.collectionView.mj_footer.hidden = YES;
    [self.collectionView reloadData];
    [self.view addSubview:self.collectionView];
    [self.view addSubview:_payButton];
    
    [_payButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view);
        make.bottom.equalTo(self.view);
        if(IS_58INCH_SCREEN)
        {
            make.bottom.equalTo(self.view).offset(-30);
        }
        make.left.and.right.equalTo(self.view);
        make.height.equalTo(@55);
    }];
    
}

//请求支付
-(void)handleDoPayEvent:(UIButton *)button
{
    payModel *model = _paylist[_selectPayItem];
    payOption *option = _payOption[_selectPayID];
    
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"pay_api" A:@"pay"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:option.id forKey:@"pid"];
    [param setObject:model.id forKey:@"rid"];

    [CYNET POSTv2:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        
        
        //判断是否是苹果内购支付
        if(KGlobalVariable.appmodel.is_ios_base == 1)
        {
            [self applePayWithDic:responseObject];
        }
        else
        {
            pay *p  = [pay modelWithJSON:[responseObject valueForKey:@"pay"]];
            if(p.is_wap == 1)
            {
                [self wapPayWithDic:p];
            }
            //app支付
            else
            {
                if(p.type == 1)//支付宝
                {
                    [self gotoAlipayWithModel:p];
                }
                else if(p.type == 2)//微信
                {
                    p.wxpay_info = [[responseObject valueForKey:@"pay"] valueForKey:@"pay_info"];
                    [self gotoWechatWithModel:p];
                }
            }
        }

        
    } failure:^(NSString *error) {
        [MBProgressHUD showTopTipMessage:error];
    } hasCache:NO];
    
//    [HUDHelper alert:ASLocalizedString(@"去往充值")];
}


//苹果内购支付
-(void)applePayWithDic:(NSDictionary *)responseObject
{
    [[IAPManager sharedIAPManager] startManager];
    [IAPManager sharedIAPManager].delegate = self;
    [[IAPManager sharedIAPManager] requestProductWithId:@"coin1"];
}

- (void)gotoAlipayWithModel:(pay *)p {
    [_payManager doAliPayWithData:p Success:^(id selfPtr) {
        
    } Error:^{
        
    }];
}

-(void)gotoWechatWithModel:(pay *)p
{
    [_payManager doWechatPayWithData:p Success:^(id selfPtr) {
        
    } Error:^{
        
    }];
}
//

//WAP支付
-(void)wapPayWithDic:(pay *)p
{
    [[UIApplication sharedApplication] openURL:safeurl(p.post_url) options:@{} completionHandler:^(BOOL success) {
        
    }];
}

-(void)getRechargeList
{
    [[HUDHelper sharedInstance] syncLoading];
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"recharge_api" A:@"get_recharge_page_data"];
     NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    @weakify(self)
    [CYNET POSTv2:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        [[HUDHelper sharedInstance] syncStopLoading];

        NSArray *list = [responseObject valueForKey:@"list"];
        _paylist = [NSArray modelArrayWithClass:[payModel class] json:list];
        
        NSArray *optList = [responseObject valueForKey:@"pay_list"];
        _payOption = [NSArray modelArrayWithClass:[payOption class] json:optList];
        [weak_self.collectionView reloadData];
        
    } failure:^(NSString *error) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [MBProgressHUD showTopTipMessage:error];
    } hasCache:NO];

}

#pragma mark ————— collection代理方法 —————
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(section == 0)
    {
        if(KGlobalVariable.appmodel.is_ios_base == 1)
        {
            return 1;
        }
        
        return _paylist.count;

    }
    else
    {
        if(KGlobalVariable.appmodel.is_ios_base == 1)
        {
            return 0;
        }
        
        return _payOption.count;
    }
//    return _logic.dataArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0)
    {
        RechargeListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([RechargeListCollectionViewCell class]) forIndexPath:indexPath];
        if(_selectPayItem == indexPath.item)
        {
            [cell setPaySelect:YES];
        }
        else
        {
            [cell setPaySelect:NO];
        }
        
        payModel *paymodel = _paylist[indexPath.item];
        [cell setModel:paymodel];
        
        return cell;
    }
    else
    {
        PayOptionCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([PayOptionCollectionViewCell class]) forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        
        payOption *option = _payOption[indexPath.row];
        cell.payname.text = option.pay_name;
        [cell.payicon sd_setImageWithURL:[cyurl safeUrl:option.icon]];
//        if(indexPath.item == 0)
//        {
//            cell.payicon.image = IMAGE_NAMED(@"icon_pay_ali");
//            cell.payname.text = ASLocalizedString(@"支付宝");
//        }
//        else
//        {
//            cell.payicon.image = IMAGE_NAMED(@"icon_pay_weixin");
//            cell.payname.text = ASLocalizedString(@"微信");
//        }
        
        cell.paySelect.hidden = YES;
        //显示选择按钮
        if(_selectPayID == indexPath.item)
        {
            cell.paySelect.hidden = NO;
        }
        return cell;
    }

}

- (CGSize)collectionView:(nonnull UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    
    if(indexPath.section == 0)
    {
        int width = KScreenWidth/2-8;
        return CGSizeMake(width,40);
    }
    else
    {
        return CGSizeMake(KScreenWidth,40);
    }

}

//创建头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                                            withReuseIdentifier:@"UICollectionViewHeader"
                                                                                   forIndexPath:indexPath];
    UILabel *tip = [[UILabel alloc] init];
    if(indexPath.section == 0)
    {
        tip.text = ASLocalizedString(@"选择金额");
    }
    else
    {
        tip.text = ASLocalizedString(@"选择支付方式");
    }
    
    //判断是否是苹果内购支付
    if(KGlobalVariable.appmodel.is_ios_base == 1)
    {
        tip.hidden = YES;
    }
    
    tip.font = DEFAULT_FONT(12);
    tip.frame = CGRectMake(10, 5, 200, 20);
    [headView removeAllSubviews];
    [headView addSubview:tip];
    headView.backgroundColor = [UIColor clearColor];
    
    return headView;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout
referenceSizeForHeaderInSection:(NSInteger)section {
    
    return CGSizeMake(KScreenWidth, 20);
}

//*******重写的时候需要走一句话
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //选择充值pay
    if(indexPath.section == 1)
    {
        _selectPayID = indexPath.item;
    }
    //选择充值金额
    else if(indexPath.section == 0)
    {
        _selectPayItem = indexPath.item;
    }
    
    [self.collectionView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[IAPManager sharedIAPManager] stopManager];
}

#pragma mark IApRequestResultsDelegate
- (void)filedWithErrorCode:(NSInteger)errorCode andError:(NSString *)error {
    NSString *errorStr = ASLocalizedString(@"支付失败");
    switch (errorCode) {
        case IAP_FILEDCOED_APPLECODE:
            NSLog(ASLocalizedString(@"用户禁止应用内付费购买:%@"),error);
            errorStr = NSStringFormat(ASLocalizedString(@"用户禁止应用内付费购买%@"),error);
            break;
            
        case IAP_FILEDCOED_NORIGHT:
            errorStr = ASLocalizedString(@"用户禁止应用内付费购买");
            NSLog(ASLocalizedString(@"用户禁止应用内付费购买"));
            break;
            
        case IAP_FILEDCOED_EMPTYGOODS:
            errorStr = ASLocalizedString(@"商品为空");
            NSLog(ASLocalizedString(@"商品为空"));
            break;
            
        case IAP_FILEDCOED_CANNOTGETINFORMATION:
            errorStr = ASLocalizedString(@"无法获取产品信息，请重试");
            NSLog(ASLocalizedString(@"无法获取产品信息，请重试"));
            break;
            
        case IAP_FILEDCOED_BUYFILED:
            errorStr = ASLocalizedString(@"购买失败，请重试");
            NSLog(ASLocalizedString(@"购买失败，请重试"));
            break;
            
        case IAP_FILEDCOED_USERCANCEL:
            errorStr = ASLocalizedString(@"用户取消交易");
            NSLog(ASLocalizedString(@"用户取消交易"));
            break;
            
        default:
            break;
    }
    [MBProgressHUD hideHUD];
    [MBProgressHUD showErrorMessage:errorStr];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
